package com.ruoyi.project.system.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.lang.UUID;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Ide;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.annotation.SignatureValidation;
import com.ruoyi.framework.aspectj.lang.enums.OperatorType;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.service.ISysBankService;
import com.ruoyi.project.system.service.ISysCompanyService;
import com.ruoyi.project.system.service.ISysReceiveService;
import io.swagger.annotations.ApiOperation;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.security.LoginUser;
import com.ruoyi.framework.security.service.SysLoginService;
import com.ruoyi.framework.security.service.SysPermissionService;
import com.ruoyi.framework.security.service.TokenService;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.service.ISysMenuService;

/**
 * 登录验证
 *
 * @author ruoyi
 */
@RestController
public class SysLoginController
{
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private SysLoginService loginService;

    @Autowired
    private ISysMenuService menuService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ISysBankService sysBankService;

    @Autowired
    private ISysReceiveService sysReceiveService;

    @Autowired
    private ISysCompanyService sysCompanyService;

    /**
     * 登录方法
     *
     * @param username 用户名
     * @param password 密码
     * @param captcha 验证码
     * @param uuid 唯一标识
     * @return 结果
     */
    @PostMapping("/login")
    public AjaxResult login(String username, String password, String code, String uuid)
    {
        AjaxResult ajax = AjaxResult.success();
        // 生成令牌
        String token = loginService.login(username, password, code, uuid);
        ajax.put(Constants.TOKEN, token);
        return ajax;
    }

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("getInfo")
    public AjaxResult getInfo()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        SysUser user = loginUser.getUser();
        // 角色集合
        Set<String> roles = permissionService.getRolePermission(user);
        // 权限集合
        Set<String> permissions = permissionService.getMenuPermission(user);
        AjaxResult ajax = AjaxResult.success();
        ajax.put("user", user);
        ajax.put("roles", roles);
        ajax.put("permissions", permissions);
        return ajax;
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public AjaxResult getRouters()
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        // 用户信息
        SysUser user = loginUser.getUser();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(user.getUserId());
        return AjaxResult.success(menuService.buildMenus(menus));
    }

    @GetMapping(value = "/getBankDetail")
    @Log(title = "获取登录用户详细信息", operatorType = OperatorType.MOBILE)
    @SignatureValidation
    @ApiOperation("获取登录用户详细信息")
    public AjaxResult getBankDetail() {
        SysBank sysBank=SecurityUtils.getLoginUser().getSysBank();
        if(null!=SecurityUtils.getLoginUser().getLoginTime()){
            Long times= SecurityUtils.getLoginUser().getLoginTime();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
            String today=simpleDateFormat.format(new Date());
            String cuurent=simpleDateFormat.format(new Date(times));
            if(!today.equals(cuurent)){
                throw new CustomException("获取用户信息异常", HttpStatus.UNAUTHORIZED);
            }
        }
        return AjaxResult.success(sysBank);
    }


/*
    @PostMapping(value = "/validLogin")
    @Log(title = "校验客户验证码", operatorType = OperatorType.MOBILE)
    @SignatureValidation
    @ApiOperation("校验客户验证码")
    public AjaxResult codeLogin(@RequestBody Map map) {
        if (null == map.get("phone")) {
            return AjaxResult.error("手机号为空");
        }
        if (null == map.get("code")) {
            return AjaxResult.error("短信验证码为空");
        }
        if (null == map.get("key")) {
            return AjaxResult.error("验证码值为空");
        }
        if (null == map.get("type")) {
            return AjaxResult.error("业务类型为空");
        }
        String verifyKey = Constants.PHONE_CODE_KEY+map.get("phone") + map.get("key");
        String captcha = redisCache.getCacheObject(verifyKey);
        if (captcha == null) {
            return AjaxResult.error("验证码失效");
        }
        if (!(map.get("code") + "").equalsIgnoreCase(captcha)) {
            return AjaxResult.error("验证码错误");
        }
        SysReceive data=new SysReceive();
        data.setStatus("1");
        data.setBankUserId(SecurityUtils.getLoginUser().getSysBank().getBankUserId());
        data.setType(map.get("type")+"");
        data.setCreateTime(new Date());
        List<SysReceive> list=sysReceiveService.selectSysReceiveList(data);
        SysCompany sysCompany=sysCompanyService.selectSysCompanyById(1l);
        if(list.size()>= Integer.valueOf(sysCompany.getScore())){
            return AjaxResult.error("领取人数已满"+list.size()+"人");
        }
        redisCache.deleteObject(verifyKey);
        return AjaxResult.success("操作成功",UUID.randomUUID().toString());
    }*/


    @PostMapping(value = "/validLogin")
    @Log(title = "校验客户验证码", operatorType = OperatorType.MOBILE)
    @SignatureValidation
    @ApiOperation("校验客户验证码")
    public AjaxResult codeLogin(@RequestBody Map map) {
        if (null == map.get("type")) {
            return AjaxResult.error("业务类型为空");
        }
        SysReceive data=new SysReceive();
        data.setStatus("1");
//        data.setBankUserId(SecurityUtils.getLoginUser().getSysBank().getBankUserId());
        data.setType(map.get("type")+"");
        data.setUpdateTime(new Date());
        List<SysReceive> list=sysReceiveService.selectSysReceiveList(data);
        SysCompany sysCompany=sysCompanyService.selectSysCompanyById(1l);
        if(list.size()>= Integer.valueOf(sysCompany.getScore())){
            return AjaxResult.error("领取人数已满"+list.size()+"人");
        }
        return AjaxResult.success("操作成功",UUID.randomUUID().toString());
    }

    public static void main(String[] args) {
        System.out.println(UUID.randomUUID());
    }
}
